package meihua.stopcarapp.ui;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import butterknife.Bind;
import butterknife.OnClick;
import meihua.mylibrary.base.BaseActivity;
import meihua.mylibrary.baseapp.AppConfig;
import meihua.mylibrary.commonutils.RxCountDown;
import meihua.stopcarapp.R;
import meihua.stopcarapp.app.UserConfig;
import meihua.stopcarapp.bean.result.UserResult;
import meihua.stopcarapp.model.LoginModel;
import meihua.stopcarapp.presenter.LoginPresenter;
import meihua.stopcarapp.presenter.contract.LoginContract;
import meihua.stopcarapp.utils.ToastUtil;
import rx.Subscriber;
import rx.functions.Action0;

/**
 * Name: LGZ
 * Time: 2017/5/9.
 * Dec:
 */

public class LoginAcivity extends BaseActivity<LoginPresenter,LoginModel> implements
        LoginContract.View, TextWatcher {

    @Bind(R.id.toolbar_left)
    ImageView toolbarLeft;
    @Bind(R.id.toolbar_center)
    TextView toolbarCenter;
    @Bind(R.id.activity_login_icon)
    ImageView activityLoginIcon;
    @Bind(R.id.activity_login_et_phone)
    EditText activityLoginEtPhone;
    @Bind(R.id.activity_login_et_code)
    EditText activityLoginEtCode;
    @Bind(R.id.activity_login_cb_read)
    CheckBox activityLoginCbRead;
    @Bind(R.id.activity_login_tv_xieyi)
    TextView activityLoginTvXieyi;
    @Bind(R.id.activity_login_btn_login)
    Button btnLogin;
    @Bind(R.id.activity_login_sendcode)
    Button btnSendCode;

    String phone;
    boolean isPhone = false;
    String userCode;
    boolean isUserCode = false;
    boolean isRead = false;
    String serviceCode;
    //倒计时事件设置（S）
    int count = 10;

    @Override
    public int getLayoutId() {
        return R.layout.activity_login;
    }

    /**
     * 入口
     *
     * @param activity
     */
    public static void startAction(Activity activity) {
        Intent intent = new Intent(activity, LoginAcivity.class);
        activity.startActivity(intent);
    }

    @Override
    public void initPresenter() {
        mPresenter.setVM(this,mModel);
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        activityLoginEtPhone.addTextChangedListener(this);
        activityLoginEtCode.addTextChangedListener(this);

    }

    @OnClick({R.id.activity_login_sendcode, R.id.activity_login_btn_login, R.id.activity_login_cb_read,
            R.id.toolbar_left})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.toolbar_left:
                LoginAcivity.this.finish();
                break;
            case R.id.activity_login_sendcode:
                sendCode();
                break;
            case R.id.activity_login_btn_login:
                login();
                break;
            case R.id.activity_login_cb_read:
                if (btnLogin.isEnabled() == false) {
                    isRead = true;
                }else {
                    isRead = false;
                }
                if (isPhone && isUserCode && isRead)
                    btnLogin.setEnabled(true);
                else
                    btnLogin.setEnabled(false);
                break;
        }
    }

    void sendCode(){
        if (!isPhone&&true){
            ToastUtil.showShort(LoginAcivity.this,"请输入正确的手机号！");
            return;
        }

        mPresenter.sendCodeRequest(phone);
        //发送短信的倒计时
        RxCountDown.countdown(count)
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        btnSendCode.setEnabled(false);
                        btnSendCode.setText(count+1+"S");
                    }
                })
                .subscribe(new Subscriber<Integer>() {
                    @Override
                    public void onCompleted() {
                        btnSendCode.setText("发送验证码");
                        btnSendCode.setEnabled(true);
                    }
                    @Override
                    public void onError(Throwable e) {
                    }
                    @Override
                    public void onNext(Integer integer) {
                        String timeStr = btnSendCode.getText().toString();
                        String subt = timeStr.substring(0,timeStr.length()-1);
                        int t = Integer.parseInt(subt);
                        btnSendCode.setText(t-1+"S");
                    }
                });
    }

    void login(){
        phone = activityLoginEtPhone.getText().toString();
        userCode = activityLoginEtCode.getText().toString();
        mPresenter.loginRequest(phone,userCode);
    }

    @Override
    public void returnPhoneCode(String code) {
        ToastUtil.showShort(LoginAcivity.this,code);
    }

    @Override
    public void returnLogin(UserResult userEntity) {
        SharedPreferences sp=getSharedPreferences("config",0);
        SharedPreferences.Editor editor=sp.edit();
        //把数据进行保
        editor.putString("login_status", AppConfig.USER_LOGIN);
        editor.putString("user_id",userEntity.getUser_id());
        editor.putString("user_phone",userEntity.getUser_phone());
        //提交数据
        editor.commit();
        //在内存中保存用户信息
        UserConfig.USER_ENTITY = userEntity;
        LoginAcivity.this.finish();
    }

    @Override
    public void showLoading(String title) {

    }

    @Override
    public void stopLoading() {

    }

    @Override
    public void showErrorTip(String msg) {

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

        phone = activityLoginEtPhone.getText().toString();
        if (phone.length() == 11) isPhone = true;
        else isPhone = false;
        userCode = activityLoginEtCode.getText().toString();
        if (userCode.length() == 6) isUserCode = true;
        else isUserCode = false;
        if (isPhone && isUserCode && isRead)
            btnLogin.setEnabled(true);
        else
            btnLogin.setEnabled(false);

    }

    @Override
    public void afterTextChanged(Editable s) {

    }
}
